import os
import subprocess
import time

# ====== 配置区域 ======
mumu_adb_path = r"E:\MuMU\MuMu Player 12\shell\adb.exe"
MUMU_DEVICE_PORT = "16384"
DEVICE_ID = None

# ====== 核心函数 ======
def get_mumu_device(max_retries=3):
    """正确获取MuMu模拟器的设备ID（自动连接+重试）"""
    global DEVICE_ID
    
    for attempt in range(max_retries):
        # ===== 自动连接MuMu模拟器 =====
        print(f"[调试] 尝试连接MuMu模拟器 (尝试 {attempt + 1}/{max_retries})...")
        connect_result = os.popen(f'"{mumu_adb_path}" connect 127.0.0.1:{MUMU_DEVICE_PORT}').read()
        print(f"[DEBUG] adb connect输出:\n{connect_result}")
        
        # 等待连接稳定
        time.sleep(1)
        
        # ===== 获取设备ID =====
        result = os.popen(f'"{mumu_adb_path}" devices').read()
        print(f"[DEBUG] adb devices输出:\n{result}")
        
        for line in result.split('\n'):
            line = line.strip()
            if line and 'device' in line and not line.startswith('List'):
                DEVICE_ID = line.split('\t')[0]
                print(f"[成功] 获取到设备ID: {DEVICE_ID}")
                return DEVICE_ID
        
        print(f"[警告] 第 {attempt + 1} 次尝试未找到设备ID，稍后重试...")
        time.sleep(2)  # 等待2秒再重试
    
    print("[错误] 多次尝试后仍无法获取设备ID")
    print("可能原因：")
    print("1. MuMu模拟器未运行或ADB服务异常")
    print("2. 端口 127.0.0.1:16384 未被占用")
    return None

def execute_adb_command(command):
    """执行ADB命令"""
    if not DEVICE_ID:
        print("错误：未获取到设备ID")
        return False
    
    full_command = f'"{mumu_adb_path}" -s {DEVICE_ID} {command}'
    print(f"[执行命令] {full_command}")
    
    try:
        result = subprocess.run(
            full_command,
            shell=True,
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        print("[命令输出]", result.stdout.strip())
        if result.stderr.strip():
            print("[命令错误]", result.stderr.strip())
        return True
    except subprocess.CalledProcessError as e:
        print(f"[命令失败] 返回码 {e.returncode}: {e.stderr.strip()}")
        return False
    except Exception as e:
        print(f"[异常] {str(e)}")
        return False

def test_connection():
    """测试ADB连接"""
    print("\n=== 开始测试 ===")
    
    if not get_mumu_device():
        print("致命错误：无法获取设备ID")
        return
    
    if not execute_adb_command("shell getprop ro.product.model"):
        print("命令执行失败")
    else:
        print("ADB命令执行成功！")
    

def test_screenshot(save_path=None):
    """测试截图功能（支持自定义保存路径）"""
    # 如果未传入路径，使用默认路径
    if save_path is None:
        save_path = (
            r"E:\game_shellPrj\AutoDerbyV1.00"
            r"\screen_shot\frome_device\xn.png"
        )
    
    print(f"\n[截图测试] 保存到: {save_path}")
    
    if not execute_adb_command("shell screencap -p /sdcard/screen.png"):
        print("截图失败(设备端)")
        return
    
    if not execute_adb_command(f"pull /sdcard/screen.png {save_path}"):
        print("截图失败(拉取文件)")
        return
    
    print("截图测试成功！")

def adb_click(x, y):
    """
    在指定坐标点击屏幕
    :param x: 横坐标
    :param y: 纵坐标
    :return: 是否执行成功
    """
    if not DEVICE_ID:
        print("错误：未获取到设备ID，请先调用get_mumu_device()")
        return False
    
    # 构造点击命令
    click_command = f"shell input tap {x} {y}"
    
    # 执行命令
    success = execute_adb_command(click_command)
    
    if success:
        print(f"成功点击坐标: ({x}, {y})")
    else:
        print(f"点击坐标失败: ({x}, {y})")
    
    return success
'''
def test_click():
    """测试点击功能"""
    print("\n=== 开始点击测试 ===")
    if not DEVICE_ID:
        print("错误：未获取到设备ID")
        return
    
    # 测试点击屏幕中心点(示例坐标，可根据实际需要修改)
    test_x, test_y = 527, 1483  # 假设屏幕分辨率为1920x1080的中心点
    
    print(f"将在坐标 ({test_x}, {test_y}) 进行点击测试...")
    if adb_click(test_x, test_y):
        print("点击测试成功！")
    else:
        print("点击测试失败")
'''